
package by.hqsoftware.RollingBall;

import by.hqsoftware.RollingBall.GraphicElements.Ball;
import by.hqsoftware.RollingBall.GraphicElements.Field;
import android.content.Context;
import android.content.res.Resources;

import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorEvent;

public class GameView extends GLSurfaceView {

	public GameView(Context context) {
		super(context);
		initialize();		
	}
	
	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initialize();
	}
	
	private Ball mBall;
	
	private long mLastTimestamp;
	private float mLastDeltaT;
	
	public float metersToPixelsX;
	public float metersToPixelsY;
		
	private Field mField;
	
	private void initialize() {
		Resources res = getContext().getResources();
				
		mBall = new Ball();
		mBall.parse(res, "Ball", R.raw.ball);
		
		mField = new Field(mBall);
		mField.parse(res, "Field", R.raw.field);		
		
		setRenderer(new GameRenderer(getContext(), mField));			
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);		
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		canvas.drawText("Points", 10, 10, 20, 20, paint);		
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {			
		super.onSizeChanged(w, h, oldw, oldh);
	}
	
	//update ball's position
	public void UpdateBallsPosition(SensorEvent event) {
		final float sensorX = event.values[0];
		final float sensorY = -event.values[1];
		
		
		final long t = event.timestamp;
        if (mLastTimestamp != 0) {
            final float dT = (float) (t - mLastTimestamp) * (1.0f / 1000000000.0f);
            if (mLastDeltaT != 0) {        
            	final float dTC = dT / mLastDeltaT;
                mBall.computePhysics(sensorX, sensorY, dT, dTC);
            }
            mLastDeltaT = dT;
        }
        mLastTimestamp = t;				
	}
}
